package com.company.http;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import java.util.Map;

public class HttpClient {
    public static HttpClient httpClient;
    private OkHttpClient.Builder okHttpBuilder;
    private Retrofit retrofit;
    public HttpClient() {
        okHttpBuilder = new OkHttpClient.Builder();
        okHttpBuilder.addInterceptor(new HeardInterceptor());
        retrofit = new Retrofit.Builder()
                .client(okHttpBuilder.build())
                //.addConverterFactory(GsonConverterFactory.create())
               // .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl("https://translate.google.cn/")
                .build();
    }

    public static HttpClient getInstant(){
        if(httpClient == null){
            synchronized (HttpClient.class){
                if(httpClient == null){
                    httpClient = new HttpClient();
                }
            }
        }
        return httpClient;
    }

    public void gogeHttp(Map<String,String> map, final ACallback callback){
        Call<ResponseBody> observable = retrofit.create(APiservice.class).get2("translate_a/single",map);
        observable.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if(response.code() == 200){
                    callback.onSuccess(response.body());
                }else {
                    callback.onFail(response.code(),"未知错误");
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                callback.onFail(10,t.getMessage());
            }
        });
    }
}
